package com.redStone.util;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;

/** 
 * @ClassName: DBUtils 
 * @Description: 数据库操作工具类
 * @author: Administrator
 */
public class DBUtil {

	private static DruidDataSource dataSource = null;
	
	static {
		// 加载数据库配置文件
		Properties prop = null;
		try {
			// 加载数据库配置文件
			prop = PropertyUtils.loadProperties("db.properties");
		} catch (IOException e) {
			System.err.println("加载数据库配置文件失败");
			//  终止JVM运行
			System.exit(-1);
		}
		
		//创建数据源
		dataSource = new DruidDataSource();
		dataSource.setDriverClassName(prop.getProperty("driverClass"));
		dataSource.setMaxActive(Integer.parseInt(prop.getProperty("maxActive")));
		dataSource.setMinIdle(Integer.parseInt(prop.getProperty("minIdel")));
		dataSource.setUrl(prop.getProperty("url"));
		dataSource.setUsername(prop.getProperty("username"));
		dataSource.setPassword(prop.getProperty("password"));
	}
	
	/**
	 * 
	* @Title: getConnection 
	* @Description: 获取数据库连接 
	* @return Connection
	* @author Administrator
	 * @throws SQLException 
	 */
	public static Connection getCon() throws SQLException {
		Connection con = dataSource.getConnection();
		return con;
	}
	
	/**
	 * 
	* @Title: release 
	* @Description: 释放数据库资源 
	* @param conn
	* @param psmt
	* @param rs void
	* @author Administrator
	 */
	public static void release(Connection conn, PreparedStatement psmt, ResultSet rs) {
		try {
			if(rs != null) {
				rs.close();
			}
			if(psmt != null) {
				psmt.close();
			}
			if(conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO :给管理员发邮件或者发送短信
		}
	}
	
}
